package com.jumi.microservice.service.admin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.SendCallback;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.common.constant.DelFlag;
import com.jumi.microservice.common.exception.BaseException;
import com.jumi.microservice.common.page.TableDataInfo;
import com.jumi.microservice.common.utils.DateUtil;
import com.jumi.microservice.common.utils.EnumUtil;
import com.jumi.microservice.constant.PayChannelEnum;
import com.jumi.microservice.constant.compensation.AfterSaleStatusEnum;
import com.jumi.microservice.constant.refundgoods.*;
import com.jumi.microservice.constant.reissue.SelfFlagEnum;
import com.jumi.microservice.domain.MessageTemplate;
import com.jumi.microservice.dto.PaymentResponse;
import com.jumi.microservice.dto.apiService.RefundOrderGoodsResponse;
import com.jumi.microservice.dto.order.OrderLogRequest;
import com.jumi.microservice.dto.RefundRequest;
import com.jumi.microservice.dto.admin.*;
import com.jumi.microservice.dto.admin.refund.*;
import com.jumi.microservice.dto.apiService.OrderGoodsResponse;
import com.jumi.microservice.dto.excel.ExportExcelCommonResponse;
import com.jumi.microservice.dto.export.ExportAfterSealRequest;
import com.jumi.microservice.dto.export.ExportAfterSealResponse;
import com.jumi.microservice.dto.reponse.UserExternalResponse;
import com.jumi.microservice.dto.serviceDto.*;
import com.jumi.microservice.entity.RefundGoods;
import com.jumi.microservice.enumerate.*;
import com.jumi.microservice.exception.RefundGoodsExceptionEnum;
import com.jumi.microservice.mapper.RefundGoodsMapper;
import com.jumi.microservice.material.dto.supplier.JmSupplierResponse;
import com.jumi.microservice.material.service.IJmSupplierService;
import com.jumi.microservice.material.service.IJmWarehouseService;
import com.jumi.microservice.rocketmq.RocketMqConfig;
import com.jumi.microservice.rocketmq.SendMessageHandler;
import com.jumi.microservice.rocketmq.domain.OrderAfterSaleEvent;
import com.jumi.microservice.rocketmq.domain.RefundAllEvent;
import com.jumi.microservice.rocketmq.domain.RefundPartEvent;
import com.jumi.microservice.service.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

/**
 * @author Scw
 * @Date 2020-08-05 11:37
 */
@Service
public class AdminRefundService {
    @Resource
    RefundGoodsMapper refundGoodsMapper;
    @DubboReference
    private IPayService iPayService;
    @DubboReference
    private IOrderDubboService iOrderDubboService;
    @DubboReference
    private IOrderService iOrderService;
    @DubboReference
    private IJmSupplierService supplyClient;
    @DubboReference
    private IJmWarehouseService warehouseClient;
    @DubboReference
    IOrderGoodsService iOrderGoodsService;
    @DubboReference
    private IUserExternalService iUserExternalService;
    @Resource
    ProducerBean producerBean;
    @Autowired
    RocketMqConfig rocketMqConfig;
    @Resource
    SendCallback callback;
    @Resource
    SendMessageHandler sendMessageHandler;

    /**
     * 退款添加--订单发起
     * 订单部分退款
     *
     * @param adminRefundRequest
     * @return
     */
    @org.springframework.transaction.annotation.Transactional
    public ResponseResult<Boolean> addRefund(AdminRefundRequest adminRefundRequest) {
        boolean refundRes = false;
        Long operatorId = adminRefundRequest.getOperatorId();
        String operatorName = adminRefundRequest.getOperatorName();
        Byte userFlag = adminRefundRequest.getUserFlag();
        /*
         * 根据订单ID查询订单状态【订单表】
         * 订单状态：0-已取消、1-待付款、2-待发货、3-待收货、4-已完成
         * 发起退款：2-待发货
         * 发起退货：3-待收货、4-已完成【待收货8天以内】
         * 补发：3-待收货、4-已完成
         * 补偿：3-待收货、4-已完成
         * 补邮：3-待收货、4-已完成
         * 换货：3-待收货、4-已完成
         * 补发漏发：3-待收货、4-已完成
         *
         */
        //根据订单ID查询订单状态【订单表】
        Integer refundOrderStatus = iOrderService.getOrderStatus(adminRefundRequest.getOrderId());
        if (refundOrderStatus != null) {
            //Integer[] notAllowArr = {0, 1, 3, 4};
            Integer[] notAllowArr = {
                    OrderStatusEnum.CANCEL.getCode().intValue(),
                    OrderStatusEnum.READY_TO_PAY.getCode().intValue(),
                    OrderStatusEnum.READY_TO_RECEIVE.getCode().intValue(),
                    OrderStatusEnum.COMPLETED.getCode().intValue()
            };
            if (Arrays.asList(notAllowArr).contains(refundOrderStatus)) {
                throw new BaseException(RefundGoodsExceptionEnum.ORDER_STATUS_NOT_ALLOW.getCode(), RefundGoodsExceptionEnum.ORDER_STATUS_NOT_ALLOW.getMessage());
            }
        }
        /*
         * 查询订单相关信息
         */
        OrderIdGoodsIdRequest orderDetailsRequest = new OrderIdGoodsIdRequest();
        orderDetailsRequest.setOrderId(adminRefundRequest.getOrderId());
        OrderGoodsEntityResponse orderDetailsResponse = iOrderService.getOrderGoodsDetails(orderDetailsRequest);
        if (orderDetailsResponse == null) {
            throw new BaseException(RefundGoodsExceptionEnum.ORDER_INFO_NO_EXIST.getCode(), RefundGoodsExceptionEnum.ORDER_INFO_NO_EXIST.getMessage());
        }
        /*
         * 订单支付类型：0-未支付 1-支付宝支付 2-微信支付 3-余额支付 4-聚合支付 5-支付宝H5支付 6-微信H5支付 7-微信小程序支付
         * 记录第三方退款相关信息：1、2、5、6、7
         */
        //Integer[] payTypeArr = {1, 2, 5, 6, 7};
        Integer[] payTypeArr = {
                PayChannelEnum.ALI_PAY.getCode().intValue(),
                PayChannelEnum.WX_PAY.getCode().intValue(),
                PayChannelEnum.ALI_PAY_H5.getCode().intValue(),
                PayChannelEnum.WX_PAY_H5.getCode().intValue(),
                PayChannelEnum.WX_PAY_LETS.getCode().intValue()
        };
        //Integer[] payTypeArr = {2, 6, 7};
        Integer[] payWxTypeArr = {
                PayChannelEnum.WX_PAY.getCode().intValue(),
                PayChannelEnum.WX_PAY_H5.getCode().intValue(),
                PayChannelEnum.WX_PAY_LETS.getCode().intValue()
        };
        /*
         * 调用聚合支付退款接口
         */
        PayChannelEnum payChannelEnum = EnumUtil.getByCode(orderDetailsResponse.getPayType(), PayChannelEnum.class);
        RefundRequest refundRequest = new RefundRequest();
        refundRequest.setUid(orderDetailsResponse.getBuyerId());
        refundRequest.setAmount(orderDetailsResponse.getPayAmount());
        refundRequest.setDesc("聚合支付退款");
        refundRequest.setPayNo(orderDetailsResponse.getPayNo());
        refundRequest.setOrderSn(orderDetailsResponse.getOrderNo());
        refundRequest.setThirdPartyPaySn(orderDetailsResponse.getThirdPartyPaySn());
        refundRequest.setPayChannel(payChannelEnum);
        if (Arrays.asList(payWxTypeArr).contains(orderDetailsResponse.getPayType().intValue())) {
            refundRequest.setPayTotalAmount(iOrderService.getPayTotalAmount(orderDetailsResponse.getPayNo()));
        }
        PaymentResponse paymentResponse = iPayService.refund(refundRequest);
        //支付成功
        if (paymentResponse.getResult()) {
            List<com.jumi.microservice.dto.admin.OrderGoodsResponse> orderGoodsResponses = orderDetailsResponse.getOrderGoodsResponses();
            List<Integer> refundIdList = new ArrayList<>();
            for (com.jumi.microservice.dto.admin.OrderGoodsResponse orderGoodsResponse : orderGoodsResponses) {
                //退款商品总金额 = 商品数量 * 商品单价
                BigDecimal refundPrice = orderGoodsResponse.getGoodsPrice().multiply(new BigDecimal(orderGoodsResponse.getGoodsAmount()));
                //商品邮费
                BigDecimal refundPostage = orderGoodsResponse.getGoodsFreightFee();
                //退款总金额 = 退款商品总金额 + 商品邮费
                BigDecimal refundTotalPrice = refundPrice.add(refundPostage);
                RefundGoods refundGoods = new RefundGoods();
                refundGoods.setBuyerId(orderDetailsResponse.getBuyerId());
                refundGoods.setOriginalOrderId(orderDetailsResponse.getId());
                refundGoods.setOriginalOrderNo(orderDetailsResponse.getOrderNo());
                refundGoods.setRefundPrice(refundPrice);
                refundGoods.setRefundNum(orderGoodsResponse.getGoodsAmount());
                refundGoods.setRefundPostage(refundPostage);
                refundGoods.setRefundTotalPrice(refundTotalPrice);
                refundGoods.setRefundOrderNo(this.generateOrderSn());
                refundGoods.setRefundReason(adminRefundRequest.getRefundReason());
                refundGoods.setRefundDesc(adminRefundRequest.getRefundDesc());
                refundGoods.setRefundGoodsId(orderGoodsResponse.getGoodsId());
                refundGoods.setRefundPromoterId(adminRefundRequest.getOperatorId());
                refundGoods.setRefundPromoterName(adminRefundRequest.getOperatorName());
                refundGoods.setSelfFlag(orderGoodsResponse.getSelfFlag());
                refundGoods.setOrderCreateTime(orderDetailsResponse.getCreateTime());
                refundGoods.setSupplierId(orderGoodsResponse.getSupplierId());
                refundGoods.setGoodsName(orderGoodsResponse.getGoodsName());
                refundGoods.setGoodsPic(orderGoodsResponse.getGoodsCoverImg());
                refundGoods.setGoodsSpec(orderGoodsResponse.getGoodsSpec());
                refundGoods.setGoodsAmount(orderGoodsResponse.getGoodsAmount());
                refundGoods.setOrderPayNo(orderDetailsResponse.getPayNo());
                refundGoods.setOrderPayType(orderDetailsResponse.getPayType());
                refundGoods.setOrderThirdPartyPaySn(orderDetailsResponse.getThirdPartyPaySn());
                refundGoods.setOrderPayTime(orderDetailsResponse.getPayTime());
                refundGoods.setRefundPromoterId(operatorId);
                refundGoods.setRefundPromoterName(operatorName);
                refundGoods.setRefundType(RefundTypeEnum.REFUND_TYPE_MONEY.getCode().byteValue());
                refundGoods.setStatus(RefundGoodsStatusEnum.STATUS_COMPLETE.getCode().byteValue());
                refundGoods.setIsGroup(orderGoodsResponse.getIsGroup());
                if (refundGoodsMapper.insert(refundGoods) > 0) {
                    /***************************订单商品相关************************/
                    /*
                     * 更新订单商品表相关信息
                     */
                    UpdateRefundInfoRequest updateRefundInfoRequest = new UpdateRefundInfoRequest();
                    updateRefundInfoRequest.setOrderId(refundGoods.getOriginalOrderId());
                    updateRefundInfoRequest.setGoodsId(refundGoods.getRefundGoodsId());
                    updateRefundInfoRequest.setReturnCount(refundGoods.getRefundNum());
                    updateRefundInfoRequest.setReturnPrice(refundGoods.getRefundPrice());
                    updateRefundInfoRequest.setReturnPostage(refundGoods.getRefundPostage());
                    updateRefundInfoRequest.setGoodsStatus(LogisticsStatusEnum.CANCEL.getCode());
                    updateRefundInfoRequest.setAfterSealStatus(AfterSaleStatusEnum.REFUND.getCode().byteValue());
                    updateRefundInfoRequest.setRefundId(refundGoods.getId());
                    iOrderService.updateRefundInfo(updateRefundInfoRequest);

                    /*
                     * 给用户服务发送消息
                     */
                    OrderAfterSaleEvent orderAfterSaleEvent = new OrderAfterSaleEvent();
                    //订单ID
                    orderAfterSaleEvent.setOrderId(orderDetailsResponse.getId());
                    //订单编号
                    orderAfterSaleEvent.setOrderNo(orderDetailsResponse.getOrderNo());
                    //skuId
                    orderAfterSaleEvent.setSkuId(orderGoodsResponse.getGoodsId());
                    //spuId
                    orderAfterSaleEvent.setSpuId(orderGoodsResponse.getSpuId());
                    //售后数量
                    orderAfterSaleEvent.setAfterNum(orderGoodsResponse.getGoodsAmount());
                    //购买数量
                    orderAfterSaleEvent.setBuyNum(orderGoodsResponse.getGoodsAmount());
//                    Object obj = JSONArray.toJSON(orderAfterSaleEvent);
//                    String json = obj.toString();
                    Message message = new Message("orderAfterSale", "", "", JSONObject.toJSONBytes(orderAfterSaleEvent));
                    producerBean.send(message);
                    /***************************订单商品相关************************/
                }
                refundIdList.add(refundGoods.getId());
            }
            /***************************订单相关************************/
            /*
             * 订单状态 已取消
             */
            iOrderService.updateOrderStatus(adminRefundRequest.getOrderId(), OrderStatusEnum.CANCEL.getCode());

            //给发票发消息
            RefundAllEvent refundAllEvent = new RefundAllEvent();
            //售后类型：0-退款 1-退货
            refundAllEvent.setAfterType(0);
            //是否全部订单：0-否 1-是
            refundAllEvent.setComplete(1);
            //订单编号
            refundAllEvent.setOrderNo(orderDetailsResponse.getOrderNo());
            Message message2 = new Message("invoice", "", "", JSONObject.toJSONBytes(refundAllEvent));
            producerBean.send(message2);

            //推送订单退款通知消息
            MessageTemplate messageTemplate = sendMessageHandler.getMessageTemplate(9);
            String appMessageContent = "";
            String stationMessageContent = "";
            if (messageTemplate != null) {
                appMessageContent = messageTemplate.getSmtAppContent().replace("{}", orderDetailsResponse.getPayAmount().toString());
                stationMessageContent = messageTemplate.getSmtMessageContent().replace("{}", orderDetailsResponse.getPayAmount().toString());
            }
            sendMessageHandler.sendMessage("", appMessageContent, stationMessageContent,
                    orderGoodsResponses.get(0).getGoodsCoverImg(), orderDetailsResponse.getBuyerId(), 9);
            /*
             * 操作日志表插入相关信息
             */
            String logInfo = "退款成功：" + orderDetailsResponse.getOrderNo();
            if (userFlag == CancelUserFlagEnum.USER_FLAG_CUSTOMER.getCode().byteValue()) {
                operatorName = "买家";
            }
            OrderLogRequest orderLogRequest = new OrderLogRequest();
            orderLogRequest.setLog(logInfo);
            orderLogRequest.setOperatorId(operatorId);
            orderLogRequest.setOperatorName(operatorName);
            orderLogRequest.setUserFlag(userFlag);
            orderLogRequest.setOrderSn(orderDetailsResponse.getOrderNo());
            iOrderDubboService.addOrderLog(orderLogRequest);
            /***************************订单相关************************/
            /*
             * 更新第三方支付相关信息
             */
            if (Arrays.asList(payTypeArr).contains(orderDetailsResponse.getPayType().intValue())) {
                UpdateWrapper<RefundGoods> refundGoodsUpdateWrapper = new UpdateWrapper<>();
                refundGoodsUpdateWrapper.in("id", refundIdList);
                RefundGoods refundGoodsPay = new RefundGoods();
                refundGoodsPay.setThirdRefundInfo(paymentResponse.getResultInfo());
                refundGoodsMapper.update(refundGoodsPay, refundGoodsUpdateWrapper);
            }
            refundRes = true;
        }
        ResponseResult<Boolean> responseResult = new ResponseResult<>();
        return responseResult.setData(refundRes);
    }

    /**
     * 退款列表
     *
     * @param request
     * @return
     */
    public TableDataInfo<AdminRefundListResponse> getRefundList(AdminRefundListRequest request) {
        QueryWrapper<RefundGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("refund_type", RefundTypeEnum.REFUND_TYPE_MONEY.getCode());
        queryWrapper.orderByDesc("id");
        //供货商类型：1-供货商【非自营】 2-仓库【自营】
        if (request.getSupplierType() != null) {
            if (request.getSupplierId() != null) {
                queryWrapper.eq("supplier_id", request.getSupplierId());
                if (request.getSupplierType() == com.jumi.microservice.constant.reissue.SupplierTypeEnum.SUPPLIER_TYPE_ONE.getCode().byteValue()) {
                    queryWrapper.eq("self_flag", SelfFlagEnum.SELF_FLAG_NO.getCode());
                }
                if (request.getSupplierType() == com.jumi.microservice.constant.reissue.SupplierTypeEnum.SUPPLIER_TYPE_TWO.getCode().byteValue()) {
                    queryWrapper.eq("self_flag", SelfFlagEnum.SELF_FLAG_YES.getCode());
                }
            }
        }
        //商品名称
        if (request.getGoodsName() != null && !"".equals(request.getGoodsName())) {
            queryWrapper.like("goods_name", request.getGoodsName());
        }
        //下单开始时间
        if (request.getCreateBeginTime() != null && !"".equals(request.getCreateBeginTime())) {
            queryWrapper.ge("order_create_time", request.getCreateBeginTime());
        }
        //下单结束时间
        if (request.getCreateEndTime() != null && !"".equals(request.getCreateEndTime())) {
            queryWrapper.le("order_create_time", request.getCreateEndTime());
        }
        //申请开始时间
        if (request.getApplyBeginTime() != null && !"".equals(request.getApplyBeginTime())) {
            queryWrapper.ge("create_time", request.getApplyBeginTime());
        }
        //申请结束时间
        if (request.getApplyEndTime() != null && !"".equals(request.getApplyEndTime())) {
            queryWrapper.le("create_time", request.getApplyEndTime());
        }
        //订单编号
        if (request.getOriginalOrderNo() != null && !"".equals(request.getOriginalOrderNo())) {
            queryWrapper.eq("original_order_no", request.getOriginalOrderNo());
        }
        //售后编号
        if (request.getRefundOrderNo() != null && !"".equals(request.getRefundOrderNo())) {
            queryWrapper.eq("refund_order_no", request.getRefundOrderNo());
        }
        IPage<RefundGoods> page = new Page<>(request.getPageNum(), request.getPageSize());
        page = refundGoodsMapper.selectPage(page, queryWrapper);
        List<RefundGoods> refundGoodss = page.getRecords();
        List<AdminRefundListResponse> result = new ArrayList<>();
        if (refundGoodss.size() > 0) {
            for (RefundGoods refundGoods : refundGoodss) {
                AdminRefundListResponse adminRefundListResponse = new AdminRefundListResponse();
                BeanUtils.copyProperties(refundGoods, adminRefundListResponse);
                //根据用户ID查询用户姓名【用户服务提供接口】
                String userName = "";
                UserExternalResponse userExternalResponse = iUserExternalService.getUserByUid(refundGoods.getBuyerId().intValue());
                if (userExternalResponse != null) {
                    userName = userExternalResponse.getNickName();
                }
                adminRefundListResponse.setUserName(userName);
                adminRefundListResponse.setAfterSale("退款完成");
                adminRefundListResponse.setOperatorTime(refundGoods.getCreateTime());
                adminRefundListResponse.setOperatorName(refundGoods.getRefundPromoterName());
                result.add(adminRefundListResponse);
            }
        }
        TableDataInfo<AdminRefundListResponse> dataInfo = new TableDataInfo<>();
        dataInfo.setRows(result);
        dataInfo.setTotal(page.getTotal());
        return dataInfo;
    }

    /**
     * 退款导出
     *
     * @param request
     * @return
     */
    public ExportExcelCommonResponse<ExportAfterSealResponse> exportAfterSealResponse(ExportAfterSealRequest request) {
        request.checkRequest();
        com.jumi.microservice.dto.excel.ExportExcelCommonResponse<ExportAfterSealResponse> exportAfterSealResponseExportExcelCommonResponse = new com.jumi.microservice.dto.excel.ExportExcelCommonResponse<>();
        QueryWrapper<RefundGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("refund_type", RefundTypeEnum.REFUND_TYPE_MONEY.getCode());
        queryWrapper.orderByDesc("id");
        //供货商类型：1-供货商【非自营】 2-仓库【自营】
        if (request.getSupplierType() != null) {
            if (request.getSupplierId() != null) {
                queryWrapper.eq("supplier_id", request.getSupplierId());
                if (request.getSupplierType() == com.jumi.microservice.constant.reissue.SupplierTypeEnum.SUPPLIER_TYPE_ONE.getCode().byteValue()) {
                    queryWrapper.eq("self_flag", SelfFlagEnum.SELF_FLAG_NO.getCode());
                }
                if (request.getSupplierType() == com.jumi.microservice.constant.reissue.SupplierTypeEnum.SUPPLIER_TYPE_TWO.getCode().byteValue()) {
                    queryWrapper.eq("self_flag", SelfFlagEnum.SELF_FLAG_YES.getCode());
                }
            }
        }
        //商品名称
        if (request.getGoodsName() != null && !"".equals(request.getGoodsName())) {
            queryWrapper.like("goods_name", request.getGoodsName());
        }
        //下单开始时间
        if (request.getCreateBeginTime() != null && !"".equals(request.getCreateBeginTime())) {
            queryWrapper.ge("order_create_time", request.getCreateBeginTime());
        }
        //下单结束时间
        if (request.getCreateEndTime() != null && !"".equals(request.getCreateEndTime())) {
            queryWrapper.le("order_create_time", request.getCreateEndTime());
        }
        //申请开始时间
        if (request.getApplyBeginTime() != null && !"".equals(request.getApplyBeginTime())) {
            queryWrapper.ge("create_time", request.getApplyBeginTime());
        }
        //申请结束时间
        if (request.getApplyEndTime() != null && !"".equals(request.getApplyEndTime())) {
            queryWrapper.le("create_time", request.getApplyEndTime());
        }
        //订单编号
        if (request.getOriginalOrderNo() != null && !"".equals(request.getOriginalOrderNo())) {
            queryWrapper.eq("original_order_no", request.getOriginalOrderNo());
        }
        //售后编号
        if (request.getRefundOrderNo() != null && !"".equals(request.getRefundOrderNo())) {
            queryWrapper.eq("refund_order_no", request.getRefundOrderNo());
        }
        //复选框选择ID
        if (request.getIdStr() != null && !"".equals(request.getIdStr())) {
            queryWrapper.in("id", request.getIdStr().split(","));
        }
        List<RefundGoods> refundGoodss = refundGoodsMapper.selectList(queryWrapper);
        List<Integer> goodsId = refundGoodss.stream().map(RefundGoods::getRefundGoodsId).collect(Collectors.toList());
        int[] goodsIdArr = goodsId.stream().mapToInt(Integer::valueOf).toArray();
        List<OrderGoodsResponse> orderGoodsResponseList = iOrderService.getGoodsIdAndGoodsName(goodsIdArr);
        List<ExportAfterSealResponse> exportAfterSealResponses = new ArrayList<>();
        for (RefundGoods refundGoods : refundGoodss) {
            ExportAfterSealResponse exportAfterSealResponse = new ExportAfterSealResponse();
            for (OrderGoodsResponse orderGoodsResponse : orderGoodsResponseList) {
                if (orderGoodsResponse.getGoodsId() != null && orderGoodsResponse.getGoodsId().equals(refundGoods.getRefundGoodsId())) {
                    exportAfterSealResponse.setGoodsName(orderGoodsResponse.getGoodsName());
                    exportAfterSealResponse.setSupplierName(orderGoodsResponse.getSupplierName());
                }
            }
            BeanUtils.copyProperties(refundGoods, exportAfterSealResponse);
//            exportAfterSealResponse.setOrderPayTime(DateUtil.format(refundGoods.getOrderPayTime(),"yyyy-mm-dd HH:mm:ss"));
            RefundReasonEnum refundReasonEnum = EnumUtil.getByCode(refundGoods.getRefundReason().intValue(), RefundReasonEnum.class);
            exportAfterSealResponse.setRefundReason(refundReasonEnum.getDesc());
            exportAfterSealResponse.setOperatorName("系统自动退款");
            exportAfterSealResponse.setOperatorTime(refundGoods.getCreateTime());
            String supplierName = "";
            if (refundGoods.getSelfFlag() == SelfFlagEnum.SELF_FLAG_NO.getCode().byteValue()) {
                //根据供应商ID查询供应商名称 【仓储服务提供接口】
                ResponseResult<JmSupplierResponse> responseResult = supplyClient.findById(refundGoods.getSupplierId().longValue());
                Object object = responseResult.getData();
                if (object != null) {
                    JmSupplierResponse jmSupplierResponse = JSON.parseObject(JSON.toJSONString(object), JmSupplierResponse.class);
                    supplierName = jmSupplierResponse.getSupplierCompanyName();
                }
            } else {
                //根据实发仓ID查询实发仓名称 【仓储服务提供接口】
                supplierName = warehouseClient.findById(refundGoods.getSupplierId().longValue()).getData() != null ? warehouseClient.findById(refundGoods.getSupplierId().longValue()).getData().getWarehouseName() : "";
            }
            exportAfterSealResponse.setSupplierName(supplierName);
            //根据用户ID查询用户姓名【用户服务提供接口】
            String userName = "";
            UserExternalResponse userExternalResponse = iUserExternalService.getUserByUid(refundGoods.getBuyerId().intValue());
            if (userExternalResponse != null) {
                userName = userExternalResponse.getNickName();
            }
            exportAfterSealResponse.setUserName(userName);
            exportAfterSealResponse.setAfterSealStatus("退款完成");
            exportAfterSealResponses.add(exportAfterSealResponse);
        }
        exportAfterSealResponseExportExcelCommonResponse.setFileName("退款记录" + System.currentTimeMillis() + ".xlsx");
        exportAfterSealResponseExportExcelCommonResponse.setData(exportAfterSealResponses);
        return exportAfterSealResponseExportExcelCommonResponse;

    }

    /**
     * 退款详情
     *
     * @param request
     * @return
     */
    public ResponseResult<AdminRefundDetailsResponse> getRefundDetails(AdminRefundIdRequest request) {
        ResponseResult<AdminRefundDetailsResponse> refundDetailsResponseResponseResult = new ResponseResult<>();
        AdminRefundDetailsResponse adminRefundDetailsResponse = new AdminRefundDetailsResponse();
        QueryWrapper<RefundGoods> refundQueryWrapper = new QueryWrapper<>();
        refundQueryWrapper.eq("id", request.getId());
        refundQueryWrapper.eq("refund_type", RefundTypeEnum.REFUND_TYPE_MONEY.getCode());
        RefundGoods refundGoods = refundGoodsMapper.selectOne(refundQueryWrapper);
        if (refundGoods != null) {
            BeanUtils.copyProperties(refundGoods, adminRefundDetailsResponse);
            adminRefundDetailsResponse.setAfterSaleStatus("已同意");
        }
        refundDetailsResponseResponseResult.setData(adminRefundDetailsResponse);
        return refundDetailsResponseResponseResult;
    }

    /**
     * 退款原因--对照字典
     */
    public Map<Integer, String> getRefundMoneyReason() {
        Map<Integer, String> m = new HashMap<>();
        m.put(RefundMoneyReasonEnum.REFUND_MONEY_REASON_REPEAT.getCode(), RefundMoneyReasonEnum.REFUND_MONEY_REASON_REPEAT.getDesc());
        m.put(RefundMoneyReasonEnum.REFUND_MONEY_REASON_NOLIKE.getCode(), RefundMoneyReasonEnum.REFUND_MONEY_REASON_NOLIKE.getDesc());
        m.put(RefundMoneyReasonEnum.REFUND_MONEY_REASON_NOTSHIPPED.getCode(), RefundMoneyReasonEnum.REFUND_MONEY_REASON_NOTSHIPPED.getDesc());
        m.put(RefundMoneyReasonEnum.REFUND_MONEY_REASON_NOGOODS.getCode(), RefundMoneyReasonEnum.REFUND_MONEY_REASON_NOGOODS.getDesc());
        m.put(RefundMoneyReasonEnum.REFUND_MONEY_REASON_OTHER.getCode(), RefundMoneyReasonEnum.REFUND_MONEY_REASON_OTHER.getDesc());
        return m;
    }

    /**
     * 生成订单号
     */
    private String generateOrderSn() {
        String time = DateUtil.getAllMSTime().substring(2);
        int randomInt = ThreadLocalRandom.current().nextInt(10, 100);
        return "TK" + time + randomInt;
    }

    /**
     * 退款添加--商品发起
     * 订单部分退款
     *
     * @param request
     * @return
     */
    public ResponseResult<Boolean> refundGoods(AdminRefundPriceRequest request) {
        boolean refundRes = false;
        Long operatorId = request.getOperatorId();
        String operatorName = request.getOperatorName();
        ResponseResult<Boolean> responseResult = new ResponseResult<>();
        String[] ids = request.getGoodsId().split(",");
        List<Integer> goodsIds = Arrays.stream(ids).map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
        List<RefundOrderGoodsResponse> refundOrderGoodsResponses = iOrderGoodsService.getRefundOrderGoods(request.getOrderId(), goodsIds);
        for (RefundOrderGoodsResponse refundOrderGoodsRespons : refundOrderGoodsResponses) {
            RefundGoods refundGoods = new RefundGoods();
            refundGoods.setBuyerId(refundOrderGoodsRespons.getBuyerId());
            refundGoods.setOriginalOrderId(refundOrderGoodsRespons.getOrderId());
            refundGoods.setOriginalOrderNo(refundOrderGoodsRespons.getOrderNo());
            refundGoods.setRefundGoodsId(refundOrderGoodsRespons.getGoodsId());
            refundGoods.setRefundPrice(refundOrderGoodsRespons.getGoodsPrice().multiply(new BigDecimal(refundOrderGoodsRespons.getGoodsAmount())));
            refundGoods.setRefundNum(refundOrderGoodsRespons.getGoodsAmount());
            refundGoods.setRefundPostage(refundOrderGoodsRespons.getGoodsFreightFee());
            refundGoods.setRefundTotalPrice(refundOrderGoodsRespons.getGoodsPrice().multiply(new BigDecimal(refundOrderGoodsRespons.getGoodsAmount())).add(refundOrderGoodsRespons.getGoodsFreightFee()));
            refundGoods.setRefundOrderNo(this.generateOrderSn());
            refundGoods.setRefundReason(request.getRefundReason());
            refundGoods.setRefundDesc(request.getRefundDesc());
            refundGoods.setRefundDesc(request.getRefundDesc());
            refundGoods.setRefundGoodsId(refundOrderGoodsRespons.getGoodsId());
            refundGoods.setRefundPromoterId(request.getOperatorId());
            refundGoods.setRefundPromoterName(request.getOperatorName());
            refundGoods.setSelfFlag(refundOrderGoodsRespons.getSelfFlag());
            refundGoods.setOrderCreateTime(refundOrderGoodsRespons.getOrderCreateTime());
            refundGoods.setSupplierId(refundOrderGoodsRespons.getSupplierId());
            refundGoods.setGoodsName(refundOrderGoodsRespons.getGoodsName());
            refundGoods.setGoodsSpec(refundOrderGoodsRespons.getGoodsSpec());
            refundGoods.setGoodsPic(refundOrderGoodsRespons.getGoodsCoverImg());
            refundGoods.setGoodsAmount(refundOrderGoodsRespons.getGoodsAmount());
            refundGoods.setOrderPayNo(refundOrderGoodsRespons.getPayNo());
            refundGoods.setOrderPayType(refundOrderGoodsRespons.getPayType());
            refundGoods.setOrderThirdPartyPaySn(refundOrderGoodsRespons.getThirdPartyPaySn());
            refundGoods.setOrderPayTime(refundOrderGoodsRespons.getPayTime());
            refundGoods.setRefundPromoterId(operatorId);
            refundGoods.setRefundPromoterName(operatorName);
            refundGoods.setRefundType(RefundTypeEnum.REFUND_TYPE_MONEY.getCode().byteValue());
            refundGoods.setStatus(RefundGoodsStatusEnum.STATUS_COMPLETE.getCode().byteValue());
            refundGoods.setIsGroup(refundOrderGoodsRespons.getIsGroup());
            if (refundGoodsMapper.insert(refundGoods) > 0) {
                /*
                 * 订单支付类型：0-未支付 1-支付宝支付 2-微信支付 3-余额支付 4-聚合支付 5-支付宝H5支付 6-微信H5支付 7-微信小程序支付
                 * 记录第三方退款相关信息：1、2、5、6、7
                 */
                //Integer[] payTypeArr = {1, 2, 5, 6, 7};
                Integer[] payTypeArr = {
                        PayChannelEnum.ALI_PAY.getCode().intValue(),
                        PayChannelEnum.WX_PAY.getCode().intValue(),
                        PayChannelEnum.ALI_PAY_H5.getCode().intValue(),
                        PayChannelEnum.WX_PAY_H5.getCode().intValue(),
                        PayChannelEnum.WX_PAY_LETS.getCode().intValue()
                };
                //Integer[] payTypeArr = {2, 6, 7};
                Integer[] payWxTypeArr = {
                        PayChannelEnum.WX_PAY.getCode().intValue(),
                        PayChannelEnum.WX_PAY_H5.getCode().intValue(),
                        PayChannelEnum.WX_PAY_LETS.getCode().intValue()
                };
                /*
                 * 调用聚合支付退款接口
                 */
                PayChannelEnum payChannelEnum = EnumUtil.getByCode(refundOrderGoodsRespons.getPayType(), PayChannelEnum.class);
                RefundRequest refundRequest = new RefundRequest();
                refundRequest.setUid(refundOrderGoodsRespons.getBuyerId());
                refundRequest.setAmount(refundOrderGoodsRespons.getGoodsPrice().multiply(new BigDecimal(refundOrderGoodsRespons.getGoodsAmount())).add(refundOrderGoodsRespons.getGoodsFreightFee()));
                refundRequest.setDesc("聚合支付退款");
                refundRequest.setPayNo(refundOrderGoodsRespons.getPayNo());
                refundRequest.setOrderSn(refundGoods.getRefundOrderNo());
                refundRequest.setThirdPartyPaySn(refundOrderGoodsRespons.getThirdPartyPaySn());
                refundRequest.setPayChannel(payChannelEnum);
                if (Arrays.asList(payWxTypeArr).contains(refundOrderGoodsRespons.getPayType().intValue())) {
                    refundRequest.setPayTotalAmount(iOrderService.getPayTotalAmount(refundOrderGoodsRespons.getPayNo()));
                }
                PaymentResponse paymentResponse = iPayService.refund(refundRequest);
                if (Arrays.asList(payTypeArr).contains(refundOrderGoodsRespons.getPayType().intValue())) {
                    UpdateWrapper<RefundGoods> refundGoodsUpdateWrapper = new UpdateWrapper<>();
                    refundGoodsUpdateWrapper.eq("id", refundGoods.getId());
                    RefundGoods refundGoodsPay = new RefundGoods();
                    refundGoodsPay.setThirdRefundInfo(paymentResponse.getResultInfo());
                    refundGoodsMapper.update(refundGoodsPay, refundGoodsUpdateWrapper);
                }
                //支付成功
                if (paymentResponse.getResult()) {
                    /*
                     * 更新订单商品表相关信息
                     */
                    RefundOrderGoodsRequest refundGoodsRequest = new RefundOrderGoodsRequest();
                    refundGoodsRequest.setGoodsId(refundOrderGoodsRespons.getGoodsId());
                    refundGoodsRequest.setRefundId(refundGoods.getId());
                    refundGoodsRequest.setOrderId(request.getOrderId());
                    refundGoodsRequest.setReturnCount(refundGoods.getRefundNum());
                    refundGoodsRequest.setReturnPrice(refundGoods.getRefundPrice());
                    refundGoodsRequest.setReturnPostage(refundGoods.getRefundPostage());
                    iOrderGoodsService.refundUpdateGoods(refundGoodsRequest);
                    /*
                     * 给用户服务发送消息
                     */
                    OrderAfterSaleEvent orderAfterSaleEvent = new OrderAfterSaleEvent();
                    //订单ID
                    orderAfterSaleEvent.setOrderId(refundOrderGoodsRespons.getOrderId());
                    //订单编号
                    orderAfterSaleEvent.setOrderNo(refundOrderGoodsRespons.getOrderNo());
                    //skuId
                    orderAfterSaleEvent.setSkuId(refundOrderGoodsRespons.getGoodsId());
                    //spuId
                    orderAfterSaleEvent.setSpuId(refundOrderGoodsRespons.getSpuId());
                    //售后数量
                    orderAfterSaleEvent.setAfterNum(refundOrderGoodsRespons.getGoodsAmount());
                    //购买数量
                    orderAfterSaleEvent.setBuyNum(refundOrderGoodsRespons.getGoodsAmount());
//                    Object obj = JSONArray.toJSON(orderAfterSaleEvent);
//                    String json = obj.toString();
                    Message message = new Message("orderAfterSale", "", "", JSONObject.toJSONBytes(orderAfterSaleEvent));
                    producerBean.send(message);

                    //给发票发消息
                    RefundPartEvent refundPartEvent = new RefundPartEvent();
                    //售后类型：0-退款 1-退货
                    refundPartEvent.setAfterType(0);
                    //是否全部订单：0-否 1-是
                    refundPartEvent.setComplete(0);
                    //订单编号
                    refundPartEvent.setOrderNo(refundOrderGoodsRespons.getOrderNo());
                    //商品skuId
                    refundPartEvent.setGoodsId(refundOrderGoodsRespons.getGoodsId());
                    Message message2 = new Message("invoice", "", "", JSONObject.toJSONBytes(refundPartEvent));
                    producerBean.send(message2);
                    //库存
                    iOrderService.cancelLogisticsAndGoods(refundOrderGoodsRespons.getOrderId(), refundOrderGoodsRespons.getGoodsId());
                    //推送商品退款通知消息
                    MessageTemplate messageTemplate = sendMessageHandler.getMessageTemplate(9);
                    String appMessageContent = "";
                    String stationMessageContent = "";
                    if (messageTemplate != null) {
                        appMessageContent = messageTemplate.getSmtAppContent().replace("{}", refundGoods.getRefundTotalPrice().toString());
                        stationMessageContent = messageTemplate.getSmtMessageContent().replace("{}", refundGoods.getRefundTotalPrice().toString());
                    }
                    sendMessageHandler.sendMessage("", appMessageContent, stationMessageContent,
                            refundGoods.getGoodsPic(), refundGoods.getBuyerId(), 9);
                    /*
                     * 操作日志表插入相关信息
                     */
                    String logInfo = "退款成功：" + refundGoods.getRefundOrderNo();
                    //用户标识，1 前端用户， 2 后端管理员
                    Byte userFlag = CancelUserFlagEnum.USER_FLAG_ADMIN.getCode().byteValue();
                    OrderLogRequest orderLogRequest = new OrderLogRequest();
                    orderLogRequest.setLog(logInfo);
                    orderLogRequest.setOperatorId(operatorId);
                    orderLogRequest.setOperatorName(operatorName);
                    orderLogRequest.setUserFlag(userFlag);
                    orderLogRequest.setOrderSn(refundOrderGoodsRespons.getOrderNo());
                    iOrderDubboService.addOrderLog(orderLogRequest);
                    refundRes = true;
                } else {
                    refundGoods.setDelFlag(DelFlag.DELETE);
                    refundGoodsMapper.updateById(refundGoods);
                }
            }
        }
        //修改完了 判断是否是去更改订单状态
        boolean result = iOrderGoodsService.judgeOrderGoodsStatus(request.getOrderId());
        if (!result) {
            //取消订单
            iOrderService.updateOrderStatus(request.getOrderId(), OrderStatusEnum.CANCEL.getCode());
        }
        responseResult.setData(refundRes);
        return responseResult;
    }
}
